/*
 * @Author: Wilbur
 * @Date: 2018-11-18 17:03:16
 * @Last Modified by: Wilbur
 * @Last Modified time: 2018-12-03 11:04:45
 */
<template>
    <div class="container lottery-editor-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="rules"
            label-width="90px"
            :disabled="false">
            <div class="form-unit">
                <div class="form-title">活动设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="title"
                    label="活动名称:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.title"
                        size="small"
                        class="task-input" />
                    <span style="display:inline-block;color:#999;margin-left:12px">*标题字数不超过40字</span>
                </el-form-item>

                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="time"
                    label="活动时间:">
                    <el-date-picker
                        v-model="formData.time"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item>
            </div>
            <div class="form-unit">
                <div class="form-title">用户设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="try_limit"
                    style="white-space: nowrap"
                    label="参与次数:">
                    <el-radio
                        size="small"
                        v-model="formData.try_limit"
                        :label="1">一人一次</el-radio>
                    <el-radio
                        size="small"
                        v-model="formData.try_limit"
                        :label="0">不限次数</el-radio>
                </el-form-item>
            </div>
            <div class="form-unit">
                <div class="form-title">奖品设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="award_rate"
                    label="中奖率:">
                    <el-input-number
                        :min="0"
                        :max="100"
                        size="small"
                        controls-position="right"
                        v-model="formData.award_rate" />
                    <span style="display:inline-block;color:#999;margin-left:12px">%（单个奖品中奖概率：总中奖率 × 该奖品数量 / 所有奖品总数量）</span>
                </el-form-item>
                <el-form-item
                    size="small"
                    label="">
                    <el-button
                        @click="fnEditLotteryItem(null)"
                        type="primary"
                        size="small">新增奖品</el-button>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="operate-baar">
                    <el-popover
                        placement="top"
                        trigger="click">
                        <div
                            class="preview-image"
                            v-loading="false"
                            :style="'background-image: url('+`${baseUrl}/__local/common%5Cqrcode?content=${escape(mobileUrl + '/lottery?lottery_no=' + lottery_no)}&__ticket=${sessionTicket}`+')'" />
                        <el-button
                            slot="reference"
                            size="medium"
                            :disabled="!lottery_no">预览</el-button>
                    </el-popover>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
        <!-- 新增奖品弹窗 -->
        <el-dialog
            title="新增奖品"
            :visible.sync="addLotteryFlag">
            <div class="add-lottery-wrap">
                <el-form
                    :model="ruleForm"
                    :rules="addRules"
                    ref="addLotteryForm"
                    label-width="100px">
                    <el-form-item
                        label="奖品名称"
                        prop="title">
                        <el-input v-model="ruleForm.title" />
                    </el-form-item>
                    <el-form-item
                        label="剩余数量"
                        prop="num">
                        <el-input-number
                            size="small"
                            :min="0"
                            controls-position="right"
                            v-model="ruleForm.num" />
                    </el-form-item>
                    <el-form-item
                        label="中奖数量"
                        prop="user_award_count">
                        <div>{{ ruleForm.user_award_count }}个</div>
                    </el-form-item>
                    <el-form-item
                        label="奖品图片"
                        prop="img">
                        <el-upload
                            class="upload-demo"
                            drag
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :http-request="fnUploadImageOfTask"
                            :show-file-list="false"
                            accept="image/*">
                            <i
                                class="el-icon-upload"
                                v-if="ruleForm.img == ''"/>
                            <div
                                v-if="ruleForm.img == ''"
                                class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div
                                class="el-upload__tip"
                                slot="tip">请上传jpg/png文件，且不超过500kb
                            </div>
                            <div
                                v-if="ruleForm.img"
                                class="uploaded-image"
                                :style="'background-image: url('+ruleForm.img+')'"/>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
            <div
                slot="footer"
                class="dialog-footer">
                <el-button
                    size="small"
                    @click="fnCancelAddLottery()">取 消</el-button>
                <el-button
                    size="small"
                    type="primary"
                    @click="fnAddLotteryItem()">{{ currentEditItem === null ? '添 加' : '保 存' }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        var validateArray = (rule, value, callback) => {
            if (!value || value.length <= 0) {
                callback(new Error(rule.message));
            } else {
                callback();
            }
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray2 = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        var uploadValidator = (rule, value, callback) => {
            if(this.uploading){
                callback(new Error('请等待图片上传完毕'));
            }else if(!this.ruleForm.img){
                callback(new Error('请上传图片'));
            }else{
                callback();
            }
        };

        return {
            lottery_no: '',
            ruleForm: {
                item_no: '',
                title: '',
                img: '',
                num: '',
                user_award_count: 0,
                status: 0,
            },
            addRules: {
                title: [
                    { required: true, message: '请输入奖品名称', trigger: 'blur' }
                ],
                num: [
                    { required: true, message: '请输入奖品剩余数量', trigger: 'blur' },
                ],
                img: [
                    { validator: uploadValidator, message: '', trigger: 'blur' }
                ],
            },
            formData: {
                title: '',
                time: ['', ''],
                try_limit: 0,
                award_rate: ''
            },
            rules: {
                title: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' }
                ],
                time: [
                    { validator: validateArray2, message: '请选择活动时间', trigger: 'blur' }
                ],
                award_rate: [
                    { required: true, message: '请输入中奖率', trigger: 'blur' }
                ]
            },
            addLotteryFlag: false,
            currentEditItem: null,//当前编辑奖品项index
            uploadTime: '',
            uploading: false,

            authResult: {},
            breadcrumbList: [
                {
                    title: "任务反馈管理",
                },
                {
                    title: "抽奖列表",
                    name: 'LotteryList',
                },
                {
                    title: '添加抽奖'
                }
            ],
            // 预览链接
            previewUrl: '',
            submitting: false,
            init: false,

            baseUrl: '',
            mobileUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.lottery_no = this.$route.query.lottery_no ? this.$route.query.lottery_no : '';
        if (this.lottery_no) {
            this.baseUrl = this.$baseUrl;
            this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? '//class.zsdx.cn' : '//task.wxhand.com';
            // TODO baseURl
            this.previewUrl = '';
            this.fnGetLottery();
        } else {
            this.init = true;
        }
    },
    methods: {
        /** 取消上传奖品 */
        fnCancelAddLottery() {
            this.resetForm('addLotteryForm');
            this.addLotteryFlag = false;
        },
        /** 添加奖品项 */
        fnAddLotteryItem() {
            this.$refs.addLotteryForm.validate(valid => {
                if (valid) {
                    if (this.currentEditItem!==null) {
                        this.$set(this.currentEditItem, this.ruleForm);
                        this.currentEditItem.item_no = this.ruleForm.item_no;
                        this.currentEditItem.title = this.ruleForm.title;
                        this.currentEditItem.img = this.ruleForm.img;
                        this.currentEditItem.num = this.ruleForm.num;
                        this.currentEditItem.user_award_count = this.ruleForm.user_award_count;
                        this.currentEditItem.status = this.ruleForm.status;
                    }
                    this.addLotteryFlag = false;
                }
            });
        },
        /** 展示弹窗 */
        fnEditLotteryItem(item) {

            if(item !== null){
                this.currentEditItem = item;
                this.ruleForm = {
                    item_no: item.item_no,
                    title: item.title,
                    img: item.img,
                    num: item.num,
                    user_award_count: item.user_award_count,
                    status: item.status,
                };
            }else{
                this.currentEditItem = null;
                this.ruleForm = {
                    item_no: '',
                    title: '',
                    img: '',
                    num: '',
                    user_award_count: 0,
                    status: 0,
                };
            }
            this.addLotteryFlag = true;
        },
        /** 重置表单 */
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        /** 获取任务 */
        fnGetLottery() {
            this.$post('/task/lottery%5Cget', {
                lottery_no: this.lottery_no
            }, resp => {
                if (resp.code == 1) {
                    let tmp = resp.data;
                    // 初始化时间
                    let time = [new Date(tmp.start_time * 1000), new Date(tmp.end_time * 1000)];

                    this.formData = {
                        title: tmp.title,
                        time: time,
                        try_limit: parseInt(tmp.try_limit),
                        award_rate: tmp.award_rate*1
                    };
                    this.init = true;
                } else {
                    this.$message({
                        type: 'warning',
                        center: true,
                        message: resp.msg
                    });
                }
            });
        },
        fnSubmit() {
            if (this.submitting) {
                return;
            }

            this.$refs.mainform.validate(valid => {
                if (valid) {
                    this.submitting = true;

                    let data = {
                        lottery_no: this.lottery_no,
                        title: this.formData.title,
                        start_time: Date.parse(this.formData.time[0])/1000,
                        end_time: Date.parse(this.formData.time[1])/1000,
                        try_limit: this.formData.try_limit,
                        award_rate: this.formData.award_rate
                    };

                    this.$post('/task/lottery%5Csave', data, resp => {
                        if (resp.code == 1) {
                            this.$message({
                                type: 'success',
                                center: true,
                                message: '新增成功'
                            });
                            this.$router.push({
                                name: 'LotteryList'
                            });
                        } else {
                            this.$message({
                                type: 'warning',
                                center: true,
                                message: resp.msg
                            });
                        }
                        this.submitting = false;
                    });

                }
            });
        },
        fnUploadImageOfTask(e){
            let timeTmp = new Date().getTime();

            this.uploadTime = timeTmp;
            let pic = new FormData();

            this.uploading = true;
            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if(this.uploadTime != timeTmp){
                        return ;
                    }
                    if (resp.code == 1) {
                        this.ruleForm.img = resp.data.url;
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                    this.uploading = false;
                }
            });
        },
    },
};
</script>

<style lang="less" scoped>
    .margin-top {
      margin-top: 15px;
    }
    .lottery-editor-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    .percent-input {
      width: 80px !important;
    }
    .task-intro-input {
      width: 750px;
    }
    .table-inner-input {
      outline: none;
      line-height: 20px;
      font-size: 14px;
      width: 100%;
      background: transparent;
      text-align: center;
      cursor: pointer;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }
    .input-width-delete {
      margin-top: 15px;
      font-size: 0;
      .task-input {
        margin-right: 10px;
      }
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
    .preview-image {
      width: 120px;
      height: 120px;
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }

    .pic-width-delete {
      margin-top: 15px;
      float: left;
      margin-right: 60px;
      display: inline-block;
      width: 500px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      .pic-unit {
        flex: 1;
        margin-right: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding: 15px;
        border-radius: 4px;
        border: 1px solid rgba(217, 217, 217, 1);
        &-index {
          width: 28px;
          height: 28px;
          background: rgba(243, 250, 255, 1);
          border: 1px solid rgba(24, 144, 255, 1);
          margin-right: 15px;
          border-radius: 28px;
          text-align: center;
          line-height: 28px;
          color: rgba(24, 144, 255, 1);
        }
        &-detail {
          flex: 1;
        }
        &-desc {
          width: 100%;
        }
        &-textarea {
          resize: none;
          width: 100%;
          height: 44px;
          line-height: 20px;
          border: 0;
          outline: 0;
        }
        .pic-value {
          width: 100%;
          height: 215px;
          background-position: center;
          background-size: contain;
          background-repeat: no-repeat;
          background-color: #f6f6f6;
          position: relative;
          .loading {
            width: 100%;
            height: 100%;
            line-height: 215px;
            background: rgba(0, 0, 0, 0.3);
            transition: opacity 0.3s ease-in-out;
          }
          .tip {
            font-size: 14px;
            color: #fff;
            line-height: 215px;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            transition: opacity 0.3s ease-in-out;
          }
          &:hover {
            .loading {
              opacity: 0;
            }
            .tip {
              opacity: 1;
            }
          }
        }
        .pic-empty-container {
          display: flex;
          width: 100%;
          height: 100%;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        .pic-empty-plus {
          font-size: 24px;
          width: 24px;
          line-height: 24px !important;
          color: rgba(0, 0, 0, 0.45);
        }
        .pic-empty-desc {
          font-size: 14px;
          color: rgba(0, 0, 0, 0.65);
          line-height: 22px;
        }
      }
    }
    .upload-list {
      margin-top: 10px;
    }
    .editor-wrap {
      position: relative;
    }
    .uploaded-image {
      width: 360px;
      height: 180px;
      background-size: 100%;
      background-position: center center;
      background-repeat: no-repeat;
      &:hover {
        .icon-delete {
          display: inline-block;
        }
      }
      .icon-delete {
        margin-top: 90px;
        transform: translateY(-50%);
        display: none;
      }
    }
</style>
<style lang="less">
    .task-intro-input {
      .ql-toolbar {
        border-radius: 4px 4px 0 0;
      }
      .ql-container {
        border-radius: 0 0 4px 4px;
      }
      .ql-toolbar.ql-show,
      .ql-container.ql-snow {
        border-color: #c0c4cc !important;
      }
    }
    .pic-unit-img {
      .el-upload--picture-card {
        border: 0;
        background-color: transparent;
        width: 100%;
        height: 100%;
      }
    }
    .avatar-uploader-customer {
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
      }
      .avatar {
        width: 100px;
        height: 100px;
        display: block;
      }
    }
    .lottery-avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
</style>
